<template>
	<view class="container">
		<!-- 用户信息区域 -->
		<view class="user-section">
			<!-- 未登录状态 -->
			<view class="user-info" @click="goLogin" v-if="!isLogin">
				<image class="avatar" src="/static/images/avatar.png" mode="aspectFill"></image>
				<view class="info-box">
					<text class="nickname">游客</text>
					<text class="tips">点击头像登录账号</text>
				</view>
			</view>
			
			<!-- 已登录状态 -->
			<view class="user-info-wrap" v-else>
				<view class="user-info">
					<image 
						class="avatar" 
						:src="userInfo.avatarUrl || '/static/images/avatar.png'" 
						mode="aspectFill"
						></image>
					<view class="info-box">
						<text class="nickname">{{userInfo.name || '用户'}}</text>
						<view class="user-detail">
							<text class="phone" v-if="userInfo.phone">{{formatPhone(userInfo.phone)}}</text>
							<text class="role">{{userInfo.role === 2 ? '管理员' : '普通用户'}}</text>
						</view>
					</view>
				</view>
				<view class="logout-btn" @click="handleLogout">
					<uni-icons type="poweroff" size="20" color="#fff"></uni-icons>
					<text>退出</text>
				</view>
			</view>
		</view>

		<!-- 订单区域 -->
		<view class="order-section">
			<view class="section-header">
				<text class="title">我的订单</text>
				<view class="more" @click="goToOrderList('all')">
					<text>查看全部</text>
					<uni-icons type="right" size="14" color="#999"></uni-icons>
				</view>
			</view>
			
			<view class="order-types">
				<view class="type-item" @click="goToOrderList('pending')">
					<view class="icon-wrap">
						<uni-icons type="shop" size="24" color="#666"></uni-icons>
						<text class="badge" v-if="orderCounts.pending > 0">{{orderCounts.pending}}</text>
					</view>
					<text>{{isAdmin ? '待送货' : '待收货'}}</text>
				</view>
				<view class="type-item" @click="goToOrderList('completed')">
					<view class="icon-wrap">
						<uni-icons type="checkbox-filled" size="24" color="#666"></uni-icons>
						<text class="badge" v-if="orderCounts.completed > 0">{{orderCounts.completed}}</text>
					</view>
					<text>已完成</text>
				</view>
				<view class="type-item" @click="goToOrderList('cancelled')">
					<view class="icon-wrap">
						<uni-icons type="close" size="24" color="#666"></uni-icons>
						<text class="badge" v-if="orderCounts.canceled > 0">{{orderCounts.canceled}}</text>
					</view>
					<text>已取消</text>
				</view>
			</view>
		</view>

		<!-- 功能区域 -->
		<view class="card-section">
			<view class="section-header">
				<text>我的服务</text>
			</view>
			<view class="grid-list">
				<view class="grid-item" @click="handleFunction('address')" v-if="!isAdmin">
					<uni-icons type="location-filled" size="28" color="#ff6b81"></uni-icons>
					<text>收货地址</text>
				</view>
				<!-- 管理员功能 -->
				<view class="grid-item" @click="handleFunction('goods')" v-if="isAdmin">
					<uni-icons type="shop-filled" size="28" color="#ff6b81"></uni-icons>
					<text>商品管理</text>
				</view>
				<view class="grid-item" @click="handleFunction('about')">
					<uni-icons type="info-filled" size="28" color="#ff6b81"></uni-icons>
					<text>关于我们</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { config } from '@/utils/config.js'

// 用户信息和登录状态
const userInfo = ref({})
const loginStatus = ref(false) // 加本地录状态

// 修改为使用本地态而不是computed
const isLogin = computed(() => loginStatus.value)
const isAdmin = computed(() => userInfo.value.role === 2)

// 订单数量统计
const orderCounts = ref({
	total: 0,      // 全部订单
	pending: 0,    // 待收货
	completed: 0,  // 已完成
	canceled: 0    // 已取消
})

// 检查登录状态
const checkLogin = () => {
	const token = uni.getStorageSync('token')
	if (!token) {
		loginStatus.value = false
		userInfo.value = {}
		return false
	}
	loginStatus.value = true
	return true
}

// 获取用户信息
const getUserInfo = async () => {
	try {
		const res = await uni.request({
			url: config.baseUrl + '/api/user/info',
			method: 'GET',
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`
			}
		})
		
		if (res.data.code === 200) {
			const data = res.data.data
			const cachedInfo = uni.getStorageSync('userInfo') || {}
			
			userInfo.value = {
				...data,
				...cachedInfo,
				avatarUrl: cachedInfo.avatarUrl || '/static/images/avatar.png',
				nickName: cachedInfo.nickName || data.nickname || '用户' + data.id,
				role: data.role || 1
			}
			
			uni.setStorageSync('userInfo', userInfo.value)
			uni.setStorageSync('userRole', data.role)
		} else {
			throw new Error(res.data.message || '获取用户信息失败')
		}
	} catch (error) {
		console.error('获取用户信息失败:', error)
		const cachedInfo = uni.getStorageSync('userInfo')
		if (cachedInfo) {
			userInfo.value = cachedInfo
		} else {
			uni.removeStorageSync('token')
			userInfo.value = {}
			loginStatus.value = false
		}
	}
}

// 获取订单统计
const getOrderStats = async () => {
	if (!isLogin.value) return
	
	try {
		const res = await uni.request({
			url: config.baseUrl + '/api/orders/stats',
			method: 'GET',
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`
			}
		})
		
		if (res.data.code === 200) {
			orderCounts.value = res.data.data
		}
	} catch (error) {
		console.error('获取订单统计失败:', error)
	}
}

// 跳转登录
const goLogin = () => {
	if (!isLogin.value) {
		uni.navigateTo({
			url: '/pages/user/login'
		})
	}
}

// 跳转到订单列表
const goToOrderList = (status) => {
	// 检查登录状态
	if (!checkLogin()) {
		return goLogin();
	}
	
	let tabIndex = 0;
	switch (status) {
		case 'pending':
			tabIndex = 1;  // 待收货/待发货
			break;
		case 'completed':
			tabIndex = 2;  // 已完成
			break;
		case 'cancelled':
			tabIndex = 3;  // 已取消
			break;
		default:
			tabIndex = 0;  // 全部
	}
	
	uni.navigateTo({
		url: `/pages/order/list?tab=${tabIndex}`
	});
}

// 处理功能点击
const handleFunction = (action) => {
	if (!isLogin.value) return goLogin()
	
	switch(action) {
		case 'address':
			uni.navigateTo({
				url: '/pages/address/list'
			})
			break
		case 'goods':
			if (!isAdmin.value) {
				return uni.showToast({
					title: '无权限访问',
					icon: 'none'
				})
			}
			uni.navigateTo({
				url: '/pages/goods/manage'
			})
			break
		default:
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
	}
}

// 处理头像点击
const handleAvatarClick = () => {
	if (isLogin.value) {
		uni.showToast({
			title: '已登录',
			icon: 'none'
		})
	} else {
		goLogin()
	}
}

// 退出登录
const handleLogout = () => {
	uni.showModal({
		title: '提示',
		content: '确定要退出登录吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const res = await uni.request({
						url: config.baseUrl + '/api/user/logout',
						method: 'POST',
						header: {
							'Authorization': `Bearer ${uni.getStorageSync('token')}`
						}
					})
					
					if (res.data.code === 200) {
						// 先重置状态
						loginStatus.value = false
						userInfo.value = {}
						// 重置订单数量
						orderCounts.value = {
							total: 0,
							pending: 0,
							completed: 0,
							canceled: 0
						}
						
						// 再清除存储
						uni.removeStorageSync('token')
						uni.removeStorageSync('userInfo')
						uni.removeStorageSync('userRole')
						
						uni.showToast({
							title: '已退出登录',
							icon: 'success'
						})
					} else {
						throw new Error(res.data.message || '退出登录失败')
					}
				} catch (error) {
					console.error('退出登录失败:', error)
					// 即使接口调用失败，也执行退出操作
					loginStatus.value = false
					userInfo.value = {}
					// ���置订单数量
					orderCounts.value = {
						total: 0,
						pending: 0,
						completed: 0,
						canceled: 0
					}
					
					uni.removeStorageSync('token')
					uni.removeStorageSync('userInfo')
					uni.removeStorageSync('userRole')
					
					uni.showToast({
						title: '退出登录失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 在页面显示时检查登录状态
onShow(() => {
	if (checkLogin()) {
		getUserInfo()
		getOrderStats()  // 改为调用新的获取订单统计方法
	}
})

// 格式化手机号码
const formatPhone = (phone) => {
	if (!phone) return ''
	return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}
</script>

<style lang="scss">
.role {
	font-size: 24rpx;
	color: rgba(255,255,255,0.8);
	padding: 4rpx 12rpx;
	background: rgba(0,0,0,0.2);
	border-radius: 20rpx;
	margin-top: 8rpx;
}

.container {
	min-height: 100vh;
	background: #f7f8fa;
	padding: 20rpx;
}

.user-section {
	background: linear-gradient(45deg, #ff6b81, #ff8597);
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	margin-bottom: 20rpx;
	
	.user-info-wrap {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.user-info {
		display: flex;
		align-items: center;
		flex: 1;
		
		.avatar {
			width: 120rpx;
			height: 120rpx;
			border-radius: 60rpx;
			border: 4rpx solid rgba(255,255,255,0.3);
		}
		
		.info-box {
			margin-left: 20rpx;
			
			.nickname {
				font-size: 32rpx;
				color: #fff;
				font-weight: bold;
				margin-bottom: 8rpx;
			}
			.tips {
				font-size: 24rpx;
				color: rgba(255,255,255,0.8);
			}
			
			.user-detail {
				display: flex;
				align-items: center;
				gap: 16rpx;
				
				.phone {
					font-size: 24rpx;
					color: rgba(255,255,255,0.8);
				}
				
				.role {
					font-size: 24rpx;
					color: rgba(255,255,255,0.8);
					padding: 4rpx 12rpx;
					background: rgba(0,0,0,0.2);
					border-radius: 20rpx;
				}
			}
		}
	}
	
	.logout-btn {
		display: flex;
		align-items: center;
		padding: 12rpx 24rpx;
		background: rgba(0,0,0,0.2);
		border-radius: 30rpx;
		margin-left: 20rpx;
		
		text {
			font-size: 24rpx;
			color: #fff;
			margin-left: 8rpx;
		}
		
		&:active {
			background: rgba(0,0,0,0.3);
		}
	}
}

.card-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		
		text {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
		}
		
		.more {
			display: flex;
			align-items: center;
			
			text {
				font-size: 24rpx;
				color: #999;
				font-weight: normal;
				margin-right: 4rpx;
			}
		}
	}
	
	.order-types {
		display: flex;
		justify-content: space-around;
		
		.type-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			position: relative;
			
			text {
				font-size: 26rpx;
				color: #666;
				margin-top: 12rpx;
			}
			
			.badge {
				position: absolute;
				top: -8rpx;
				right: -16rpx;
				background: #ff6b81;
				color: #fff;
				font-size: 20rpx;
				height: 32rpx;
				min-width: 32rpx;
				padding: 0 8rpx;
				border-radius: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
	
	.grid-list {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 30rpx;
		
		.grid-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx 0;
			
			text {
				font-size: 26rpx;
				color: #666;
				margin-top: 12rpx;
			}
		}
	}
}

.user-info {
	cursor: pointer;  // 添加手型光标
	
	&:active {
		opacity: 0.8;  // 添加点击效果
	}
}

.order-section {
	background: #fff;
	margin: 20rpx;
	border-radius: 12rpx;
	padding: 30rpx;
	
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		
		.title {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
		}
		
		.more {
			display: flex;
			align-items: center;
			
			text {
				font-size: 24rpx;
				color: #999;
				margin-right: 4rpx;
			}
		}
	}
	
	.order-types {
		display: flex;
		justify-content: space-around;
		
		.type-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.icon-wrap {
				position: relative;
				margin-bottom: 12rpx;
				
				.badge {
					position: absolute;
					top: -10rpx;
					right: -16rpx;
					background: #ff6b81;
					color: #fff;
					font-size: 20rpx;
					height: 32rpx;
					min-width: 32rpx;
					padding: 0 6rpx;
					border-radius: 16rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			
			text {
				font-size: 26rpx;
				color: #333;
			}
		}
	}
}
</style> 